<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>客服聊天窗口</title>

    <link href="../../resource/css/bootstrap.min.css?v=3.3.5" rel="stylesheet"
          th:href="@{/resource/css/bootstrap.min.css?v=3.3.5}"/>
    <link href="../../resource/hotui/css/font-awesome.min.css" rel="stylesheet"
          th:href="@{/resource/hotui/css/font-awesome.min.css}">

    <link href="../../resource/css/plugins/jsTree/style.min.css" th:src="@{/resource/css/plugins/jsTree/style.min.css}"
          rel="stylesheet">

    <!-- Morris -->
    <link href="../../resource/hotui/css/plugins/morris/morris-0.4.3.min.css"
          rel="stylesheet" th:href="@{/resource/hotui/css/plugins/morris/morris-0.4.3.min.css}">
    <link href="../../resource/css/animate.min.css" rel="stylesheet" th:href="@{/resource/css/animate.min.css}"/>
    <link href="../../resource/hotui/css/style.min-1.0.8.css" rel="stylesheet"
          th:href="@{/resource/hotui/css/style.min-1.0.8.css}">
    <link href="../../resource/hotui/css/hotui.style.override.css"
          rel="stylesheet" th:href="@{/resource/hotui/css/hotui.style.override.css}"/>
    <link href="../../resource/hotui/js/plugins/datetimepick/css/daterangepicker.css"
          rel="stylesheet" th:href="@{/resource/hotui/js/plugins/datetimepick/css/daterangepicker.css}"/>
    <style>
        .chat-message-form {
            padding: 20px;
            display: flex;
            flex-direction: row;
            align-content: center;
            height: 90px;
            width: 100%;
            position: relative;
        }

        .chat-avatar {
            border-radius: 5px;
        }

        .chat-message-form .form-group {
            position: absolute;
            right: 10px;
            width: 100%;
        }

        .chat-message-box {
            position: relative;
            margin-bottom: 10px;
        }

        .chat-message-box .avatar {
            position: absolute;
            left: 0px;
            top: 0px;
            width: 40px;
            height: 40px;
            border-radius: 5px;
        }

        .my-chat-message-box .avatar {
            left: initial !important;
            right: 0;
        }

        .my-chat-message-box .message-box {
            padding-left: inherit;
            padding-right: 50px;
        }

        .my-chat-message-box .message-box .user-nick {
            text-align: right;
        }

        .my-chat-message-box .message-box .content-box {
            text-align: right;
        }

        .chat-message-box .message-box {
            padding-left: 50px;
        }

        .chat-message-box .message-box .user-nick {
            font-size: 12px;
            color: #CCCCCC;
            display: block;
            margin-bottom: 3px;
        }

        .chat-message-box .message-box .content-box {
            width: 100%;
        }

        .chat-message-box .message-box .content-box .content {
            display: inline-block;
            padding: 10px;
            background-color: #ffffff;
            border-radius: 5px;
            font-size: 12px;
        }


        .chat-message-box .message-box .content-box .image {
            width: 200px;
            height: 100px;
        }

        .chat-message-box .message-box .content-box .video {
            width: 200px;
            height: 100px;
        }

        .chat-user-selected {
            background-color: #fafafa !important;
        }

        .row {
            margin-left: initial !important;
            margin-right: initial !important;
        }

        .chat-user {
            cursor: pointer;
            position: relative;
        }

        .no-read-count {
            position: absolute;
            display: none;
            /*padding: 5px;*/
            background-color: #ff0000;
            border-radius: 50%;
            right: 10px;
            top: 15px;
            color: #ffffff;
            width: 20px;
            height: 20px;
            line-height: 20px;
            text-align: center;
            font-size: 12px;
        }

        .show-count {
            display: inline-block !important;
        }

        .chat-user-name {
            display: flex;
            flex-direction: column;
        }

        .chat-user-name .nick {
            font-size: 13px;
            font-weight: 600;
        }

        .chat-avatar {
            margin-top: 10px;
        }

        .last-message {
            font-size: 12px;
            color: #CCCCCC;
        }

        .clamp {
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            display: block;
        }

        .time-box {
            font-size: 12px;
            margin-top: 4px;
            margin-left: 50px;
        }

        .my-chat-message-box .time-box {
            text-align: right;
            margin-left: initial;
            margin-right: 50px;
        }

    </style>
</head>

<body class="gray-bg">
<div class="wrapper wrapper-content  animated fadeInRight">
    <div class="row">
        <div class="col-sm-12">
            <div class="ibox chat-view">
                <div class="ibox-title">聊天窗口
                    <small class="pull-right text-muted" id="currentUserNick"></small>
                </div>
                <div class="ibox-content" style="height: 100%">
                    <!--            人数-->
                    <div class="row" style="margin-left: initial;margin-right: initial">
                        <div class="col-md-3" style="width: 300px; padding-right: initial;padding-left: inherit">
                            <div class="chat-users" style="margin-left: inherit;height: 600px">
                                <div class="users-list" id="users-list">

                                </div>
                            </div>
                        </div>
                        <!--聊天内容-->
                        <div class="col-md-9" style="width: calc(100% - 300px);padding: 0 1px;">
                            <div class="chat-discussion" id="chat-discussion" style="height: 500px;">

                            </div>
                            <!--回复按钮-->
                            <div class="row" style="margin-left: initial;margin-right: initial">
                                <div class="col-sm-12">
                                    <div class="chat-message-form">
                                        <div class="form-group"
                                             style="display: flex;flex-direction: row;align-content: center">
                                        <textarea style="height: 60px !important;" id="chat_message"
                                                  class="form-control message-input" name="message"
                                                  placeholder="输入消息内容，按回车键发送"></textarea>
                                            <button onclick="contactHandler.sendMessage()" class="btn-success"
                                                    style="margin-left: 5px; width: 100px;height: 60px;">发送
                                            </button>
                                            <button onclick="contactHandler.onChooseImage()" class="btn-success"
                                                    style="margin: 0 5px;width: 100px;height: 60px;">选择图片
                                            </button>
                                            <button onclick="contactHandler.onChooseVideo()" class="btn-success"
                                                    style="width: 100px;height: 60px;">选择视频
                                            </button>

                                            <input class="file" type="file" id="fileVideo" name="img"
                                                   style="display: none;"
                                                   accept="video/mp4" view-element="#fileVideo"
                                                   val-element="#url1"/>
                                            <input class="file" type="file" id="fileImage" name="img"
                                                   style="display: none;"
                                                   accept="image/*" view-element="#fileImage"
                                                   val-element="#url2"/>

                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>


                </div>

            </div>
        </div>

    </div>


</div>
<!--聊天组模板-->
<script type="text/html" id="chat_template">
    <div class="chat-user {className}" onclick="contactHandler.openChat({userId},'{groupId}','{name}')">
        <img class="chat-avatar" src="{face}"/>
        <div class="chat-user-name">
            <a class="nick">{name}</a>
            <span class="last-message clamp">{message}</span>
            <span class="no-read-count {displayClass}">{noReadCount}</span>
        </div>
    </div>
</script>
<!--聊天内容模板-->
<script type="text/html" id="chat_message_template">
    <div class="chat-message-box {className}">
        <img class="avatar" src="{face}" alt=""/>
        <div class="message-box">
            <div class="user-nick">{name}</div>
            <div class="content-box">
                <span style="display: {display}" class="content">{message}</span>
                <img onclick="contactHandler.priview('{src}')" style="display: {imageDisplay}" class="image" src="{src}"
                     alt="">
                <img onclick="contactHandler.priview('{src}')" style="display: {videoDisplay}" class="video"
                     src="{video}" alt="">
            </div>
        </div>
        <div class="time-box">{time}</div>
    </div>
</script>

<!--基础框架js-->
<script src="../../resource/js/jquery.min.js?v=2.1.4" th:src="@{/resource/js/jquery.min.js?v=2.1.4}"></script>
<script src="../../resource/js/bootstrap.min.js?v=3.3.5" th:src="@{/resource/js/bootstrap.min.js?v=3.3.5}"></script>
<script src="../../resource/hotui/js/hot/bootstrap.hot.extra-utils.js"
        th:src="@{/resource/hotui/js/hot/bootstrap.hot.extra-utils.js(123123)}"></script>
<script src="../../resource/hotui/js/hot/bootstrap.hot.extra-init.js"
        th:src="@{/resource/hotui/js/hot/bootstrap.hot.extra-init.js}"></script>
<!--<script src="../../resource/hotui/js/content.min.js" th:src="@{/resource/hotui/js/content.min.js}"></script>-->
<script src="../../resource/lib/moment.min.js" th:src="@{/resource/lib/moment.min.js}"></script>
<script src="../../resource/hotui/js/plugins/datetimepick/js/daterangepicker.js"
        th:src="@{/resource/hotui/js/plugins/datetimepick/js/daterangepicker.js}"></script>


<script src="../../resource/hotui/js/plugins/ajaxfileupload.js"
        th:src="@{/resource/hotui/js/plugins/ajaxfileupload.js}"></script>

<script th:inline="javascript" type="text/javascript">
    const merchantUserId = /*[[${merchantUserId}]]*/  0;
    const pageIndex = /*[[${pageIndex}]]*/  1;
    const totalPages = /*[[${totalPages}]]*/  0;
    const pageUri = /*[[@{/contact/list}]]*/  "";
    const contactUri = /*[[@{/contact}]]*/  "";
    const uploadUri = /*[[@{/resource/upload}]]*/  "";
</script>
<script>
    //当前打开的userId
    let currentUserId = 0;
    let currentGroupId = '';
    let currentUserNick = "";
    let localMessageList = [];
    let contactHandler = {
        init() {
            hot.loading.show();
            contactHandler.chatList();
            //定时刷新聊天数据
            setInterval(function () {
                contactHandler.chatList();
                contactHandler.openChat(currentUserId, currentGroupId, currentUserNick);
            }, 2500);


            $("#chat_message").on("keypress", function (event) {
                if (event.keyCode === 13) {
                    contactHandler.sendMessage();
                }
            });


            $(".file").change(function () {
                let $view = $(this).attr('view-element');
                debugger
                hot.fileUpload(uploadUri, $(this).attr('id'), null, function (apiResult) {
                    if (apiResult.resultCode === 2000) {
                        //覆盖图片
                        if ($view === "#fileImage") {
                            contactHandler.sendFile("image", apiResult.data.previewUrl);
                        }
                        if ($view === "#fileVideo") {
                            contactHandler.sendFile("video", apiResult.data.previewUrl);
                        }
                    }
                });
            });
        },

        sendFile(type, url) {
            let requestData = {
                userId: currentUserId,
                groupId: currentGroupId,
                message: url,
                type: type
            };
            hot.loading.show();
            this.ajax(contactUri + "/history/add", requestData, function (apiResult) {
                if (apiResult.resultCode === 2000) {
                    localMessageList = [];
                    contactHandler.openChat(currentUserId, currentGroupId, currentUserNick);
                    hot.loading.close();
                    hot.tip.success("发送成功");
                    $("#chat_message").val("");
                } else {
                    hot.loading.close();
                    hot.tip.error(apiResult.resultMsg);
                }
            }, function () {
                hot.loading.close();
            }, "post");
        },

        /**
         * 获取聊天窗口
         */
        chatList() {
            this.ajax(contactUri + "/chat/list", {}, function (apiResult) {
                if (apiResult.resultCode === 2000) {
                    let chatHtml = '';
                    let template = $("#chat_template").html();
                    let list = apiResult.data || [];
                    $.each(list, function (i, item) {
                        if (item.lastReplyMessage && item.lastReplyMessage.length >= 0) {
                            chatHtml += template;
                            chatHtml = chatHtml.replace(/{groupId}/gm, item.groupId);
                            chatHtml = chatHtml.replace(/{userId}/gm, item.userBasic.userId);
                            chatHtml = chatHtml.replace(/{face}/gm, item.userBasic.avatar);
                            chatHtml = chatHtml.replace(/{name}/gm, item.userBasic.nickName);
                            chatHtml = chatHtml.replace(/{message}/gm, item.lastReplyMessage || '');
                            chatHtml = chatHtml.replace(/{noReadCount}/gm, item.noReadCount);
                            chatHtml = chatHtml.replace(/{displayClass}/gm, item.noReadCount > 0 ? 'show-count' : '');
                            if (currentUserId === item.userBasic.userId) {
                                chatHtml = chatHtml.replace(/{className}/gm, 'chat-user-selected');
                            } else {
                                chatHtml = chatHtml.replace(/{className}/gm, '');
                            }
                        }
                    });
                    $("#users-list").html(chatHtml);
                    hot.loading.close();
                } else {
                    hot.loading.close();
                    hot.tip.error(apiResult.resultMsg);
                }
            }, function () {
                hot.loading.close();
            }, "post");
        },
        /**
         * 打开聊天窗口
         * @param userId
         * @param groupId
         * @param nick 用户昵称
         */
        openChat(userId, groupId, nick) {
            if (parseInt(userId) <= 0) {
                return;
            }
            if (currentUserId !== userId) {
                localMessageList = [];
            }
            currentUserId = userId;
            currentGroupId = groupId;
            currentUserNick = nick;
            $("#currentUserNick").text("正在和 " + currentUserNick + " 沟通");
            let requestData = {
                userId: userId,
                page: 1,
                size: 100
            };
            this.ajax(contactUri + "/history/message", requestData, function (apiResult) {
                if (apiResult.resultCode === 2000) {
                    hot.loading.close();
                    let messageHtml = '';
                    let template = $("#chat_message_template").html();
                    let messageList = (apiResult.data || []).reverse();
                    if (localMessageList.length > 0 && messageList.length > 0 && messageList[messageList.length - 1].id === localMessageList[localMessageList.length - 1].id) {
                        return;
                    }
                    localMessageList = messageList;
                    $.each(messageList, function (i, item) {
                        messageHtml += template;
                        messageHtml = messageHtml.replace(/{name}/gm, item.name);
                        messageHtml = messageHtml.replace(/{face}/gm, item.face);
                        messageHtml = messageHtml.replace(/{time}/gm, item.time);
                        if (merchantUserId === item.userId) {
                            messageHtml = messageHtml.replace(/{className}/gm, 'my-chat-message-box');
                        } else {
                            messageHtml = messageHtml.replace(/{className}/gm, '');
                        }

                        if (item.type === 'image') {
                            messageHtml = messageHtml.replace(/{display}/gm, 'none');
                            messageHtml = messageHtml.replace(/{videoDisplay}/gm, 'none');
                            messageHtml = messageHtml.replace(/{imageDisplay}/gm, 'inline-block');
                            messageHtml = messageHtml.replace(/{src}/gm, item.message);
                            messageHtml = messageHtml.replace(/{video}/gm, item.message);
                        }
                        if (item.type === 'video') {
                            messageHtml = messageHtml.replace(/{display}/gm, 'none');
                            messageHtml = messageHtml.replace(/{videoDisplay}/gm, 'inline-block');
                            messageHtml = messageHtml.replace(/{imageDisplay}/gm, 'none');
                            messageHtml = messageHtml.replace(/{src}/gm, item.message);
                            messageHtml = messageHtml.replace(/{video}/gm, item.message + '?x-oss-process=video/snapshot,t_0,m_fast,ar_auto');
                        }
                        if (item.type === 'general') {
                            messageHtml = messageHtml.replace(/{message}/gm, item.message);
                            messageHtml = messageHtml.replace(/{display}/gm, 'inline-block');
                            messageHtml = messageHtml.replace(/{videoDisplay}/gm, 'none');
                            messageHtml = messageHtml.replace(/{imageDisplay}/gm, 'none');
                            messageHtml = messageHtml.replace(/{src}/gm, '');
                            messageHtml = messageHtml.replace(/{video}/gm, '');
                        }
                        if (item.type === 'contactGoods') {
                            messageHtml = messageHtml.replace(/{message}/gm, "咨询的商品名称：" + item.message + " ，商品ID：" + item.productId);
                        }
                        if (item.type === 'contactOrder') {
                            messageHtml = messageHtml.replace(/{message}/gm, "订单号：" + item.message);
                        }
                    });
                    $("#chat-discussion").html(messageHtml);
                    $('#chat-discussion').scrollTop($('#chat-discussion')[0].scrollHeight);
                } else {
                    hot.loading.close();
                    hot.tip.error(apiResult.resultMsg);
                }
            }, function () {
                hot.loading.close();
            }, "get");
        },
        /**
         * 发送消息
         */
        sendMessage() {
            let message = $.trim($("#chat_message").val());
            if (parseInt(currentUserId) <= 0 || currentGroupId.length === 0 && message.length === 0) {
                if (parseInt(currentUserId) <= 0) {
                    hot.tip.error("请先选择会话");
                } else {
                    hot.tip.error("请输入回复内容");
                }
                return;
            }
            let requestData = {
                userId: currentUserId,
                groupId: currentGroupId,
                message: message
            };
            hot.loading.show();
            this.ajax(contactUri + "/history/add", requestData, function (apiResult) {
                if (apiResult.resultCode === 2000) {
                    localMessageList = [];
                    contactHandler.openChat(currentUserId, currentGroupId, currentUserNick);
                    hot.loading.close();
                    hot.tip.success("发送成功");
                    $("#chat_message").val("");
                } else {
                    hot.loading.close();
                    hot.tip.error(apiResult.resultMsg);
                }
            }, function () {
                hot.loading.close();
            }, "post");
        },
        ajax(url, data, success, error, type) {
            let op = {
                type: type,
                url: url,
                data: data,
                dataType: 'json',
                success: function (data) {
                    if (data == null || data == undefined) {
                        if (typeof error == 'function')
                            error();
                    } else {
                        if (typeof success == 'function')
                            success(data);
                    }
                },
                error: function () {
                    error();
                }
            };
            $.ajax(op);
        },
        priview(url) {
            open(url, '_blank');
        },
        onChooseImage() {
            if (parseInt(currentUserId) <= 0 || currentGroupId.length === 0) {
                hot.tip.error("请先选择会话");
                return;
            }
            $('#fileImage').click();
        },
        onChooseVideo() {
            if (parseInt(currentUserId) <= 0 || currentGroupId.length === 0) {
                hot.tip.error("请先选择会话");
                return;
            }
            $('#fileVideo').click();
        }
    };
    $(function () {
        //初始化
        contactHandler.init();

    });

</script>

</body>

</html>
